import os
import urllib.request
import urllib.error
import re
import time
from .name_normalizer import NameNormalizer
from .config import get_moddata_path
from .curseforge import get_mod_slug

class ModSearcher:
    def __init__(self):
        self.normalizer = NameNormalizer()
        self.last_api_call_time = 0
    
    def search_mod_via_mcmod_api(self, displayName):
        """
        通过MC百科搜索API查找mod信息
        """
        # 确保距离上次API调用至少1秒
        current_time = time.time()
        time_since_last_call = current_time - self.last_api_call_time
        if time_since_last_call < 0.5:
            time.sleep(0.5 - time_since_last_call)
        self.last_api_call_time = time.time()
        
        try:
            # 构建搜索URL
            search_url = f"https://search.mcmod.cn/s?key={urllib.parse.quote(displayName)}&filter=1&mold=1"
            headers = {
                'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
            }
            
            req = urllib.request.Request(search_url, headers=headers)
            response = urllib.request.urlopen(req, timeout=10)
            content = response.read().decode('utf-8')
            
            from bs4 import BeautifulSoup
            soup = BeautifulSoup(content, 'html.parser')
            # 查找搜索结果中的链接
            links = []
            class_category_divs = soup.find_all('div', class_='head')
            for div in class_category_divs:
                category_links = div.find_all('a', href=re.compile(r'/class/\d+\.html'))
                links.extend(category_links)
            
            # 提取displayName的字母部分用于比较
            normalized_display_name = self.normalizer.extract_letters_only(displayName)
            
            # 检查至多3条搜索结果
            for i, link in enumerate(links[:3]):
                # 获取链接文本
                link_text = link.get_text()
                parts = []
                found = False
                # 查找括号中的内容
                bracket_match = re.search(r'\((.*?)\)', link_text)
                if bracket_match:
                    found = True
                    # 如果有括号，使用括号中的内容进行比较
                    bracket_content = bracket_match.group(1)
                    
                    parts.append(bracket_content.split('(')[0])
                    # 例如："落叶 (FallingLeaves (Fabric))" -> "FallingLeaves"
                    # 如果括号内容中包含 / ，则以 / 分为两部分，其中任意一部分相似度>= 90，即算找到
                # 如果没有括号，去除方括号及其中内容后进行比较
                # 移除方括号及其内容，例如 [MTR] Moog's TemplesReimagined -> Moog's TemplesReimagined
                text_without_brackets = re.sub(r'\[.*?\]', '', link_text)
                if text_without_brackets and not found:
                    # 如果去除方括号后包含'-'，则提取左边的字符串
                    # 例如："Brutal Bosses - Custom Bosses" -> "Brutal Bosses"
                        text_without_brackets = text_without_brackets.split('-')[0]
                        parts.append(text_without_brackets)  
                for part in parts:
                    # 提取部分的字母部分
                    normalized_part = self.normalizer.extract_letters_only(part)
                    # 比较字母部分是否相似度达到90%及以上
                    similarity = self.normalizer.calculate_similarity(normalized_display_name, normalized_part)
                    if similarity >= 90:
                        # 提取WikiId
                        href = link.get('href')
                        wiki_id_match = re.search(r'/class/(\d+)\.html', href)
                        if wiki_id_match:
                            wiki_id = wiki_id_match.group(1)
                            print(f"  通过MC百科搜索API找到匹配项: {link_text} (相似度: {similarity:.2f}%)")
                            return int(wiki_id)
            
            return None
        except Exception as e:
            print(f"  MC百科搜索API调用失败: {e}")
            return None
    
    def search_wiki_id(self, mod_file_path, displayName , modid):
        """
        在ModData.txt中搜索mod信息
        """
        
        # 确保使用正确的ModData.txt路径
        moddata_path = get_moddata_path()
            
        try:
            with open(moddata_path, 'r', encoding='utf-8') as f:
                slug = get_mod_slug(mod_file_path)
                normalized_displayName = self.normalizer.extract_letters_only(displayName)
                for line_num, line in enumerate(f, 1):
                    if slug and slug in line:
                        line_text = re.split("[|@¨]", line)
                        for linetext in line_text:
                            if slug == linetext.strip():
                                # print(f"  在ModData.txt中找到匹配项: {linetext}")
                                return line_num,"moddata"
                    normalized_line =self.normalizer.extract_letters_only(line)
                    if normalized_displayName in normalized_line:
                        line_text = re.split("[|@¨]", line)
                        for linetext in line_text:
                            bracket_match = re.search(r'\((.*?)\)', linetext)
                            if bracket_match:
                                line_text.extend(bracket_match.group(1).split('/'))
                            if linetext.isspace():
                                continue
                            if re.search(r'[\u4e00-\u9fa5]', linetext):
                                continue
                            pattern = re.compile('neoforge|forge|fabric|mc|mod|quilt')
                            normalized_text = pattern.sub("", self.normalizer.extract_letters_only(linetext))
                            displayName_similarity = self.normalizer.calculate_similarity(normalized_displayName,normalized_text)
                            # print(f"  正在使用文件名规范化搜索: {line_text}")
                            # 行号即为WikiId
                            if  displayName_similarity>=90 :
                                # print(f"  通过文件名规范化搜索找到匹配项: {normalized_text} (行号: {line_num})")
                                wiki_id = line_num
                                return wiki_id, "moddata"
                
                    
                
                # 如果displayName搜索失败，尝试使用MC百科搜索API
                if displayName:
                    displayName = displayName.replace("mod", "")
                    wiki_id = self.search_mod_via_mcmod_api(displayName)
                    if wiki_id:
                        return wiki_id, "mcmod_api"
                    elif modid:
                        wiki_id = self.search_mod_via_mcmod_api(modid)
                        if wiki_id:
                            return wiki_id, "mcmod_api"
            
        except Exception as e:
            print(f"读取 {moddata_path} 时出错: {e}")
        return None, None